import 'package:business_render/routes/render_pages.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:lib_core/ext/string_ext.dart';
import 'package:lib_core/lib_core.dart';
import 'package:lib_ui/common/page/common_stateful_page.dart';
import 'package:lib_ui/lib_ui.dart';
import 'package:lib_ui/widget/transparent_app_bar.dart';

class DidUpdateWidgetPage extends StatefulWidget {
  const DidUpdateWidgetPage({super.key});

  @override
  State<DidUpdateWidgetPage> createState() => _DidUpdateWidgetPageState();
}

class _DidUpdateWidgetPageState extends State<DidUpdateWidgetPage> {
  String text1 = "1";
  String text2 = "2";
  Color color1 = Colors.blue;
  Color color2 = Colors.green;
  bool flag1 = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TransparentAppBar(title: 'DidUpdateWidget触发'),
      body: SizedBox(
        width: Get.width,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            MyStatefulWidget(text: flag1 ? text1 : text2, color: flag1 ? color1 : color2),
            TextButton(
              onPressed: () {
                flag1 = !flag1;
                setState(() {});
              },
              child: Text('改变样式', style: LDFont.regular()),
            ),
          ],
        ),
      ),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  String text;
  Color color;

  MyStatefulWidget({super.key, required this.text, required this.color});

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  @override
  Widget build(BuildContext context) {
    return Text(widget.text, style: TextStyle(color: widget.color));
  }

  /// 他的触发时机是在widget树中，父组件类型没有变化时，父组件重建，下面的子组件类型也没变化，但是配置变了，就会触发
  /// 此例子里，父组件没变化是指setState后，MyStateful的父组件还是Column；配置变了，是指传的参数变了
  /// 如果setState的逻辑是将Column的第一个widget改成别的类型，或者用其他组件包裹MyStatefulWidget，则该MyStatefulWidget的didUpdateWidget是不会触发，
  /// 第一种情况是父组件发现他下面的子组件类型不一样了，无法复用以前子组件的state了，所以之前的子组件的state就销毁了（除非子组件设置了GlobalKey强制复用）
  /// 第二种情况是整个父组件的state都销毁了，他地下的子组件state也跟着销毁（除非子组件设置了GlobalKey强制复用）
  @override
  void didUpdateWidget(covariant MyStatefulWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    '触发了didUpdateWidget'.showSuccess();
  }
}
